package com.ht.yml.tools;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.Map;

/**
 * @author wangmin
 * @discription
 * @created 2024-12-30 10:04
 */
public class ApolloConfigUtils {
    public static String loadConfigContent(String appId, String namespace) {
        final String apolloUrl = "http://36.133.143.102:18082/configs/"+appId+"/default/"+namespace+"?ip=192.168.8.22";
        return loadConfigContent(apolloUrl);
    }
    public static String loadConfigContent(String apolloUrl) {
        String httpRes = HttpUtil.get(apolloUrl);
        JSONObject jo = JSON.parseObject(httpRes);
        return jo.getJSONObject("configurations").getString("content");
    }

    public static Map<String, Object> loadApolloConfig(final String appId, final String namespace) {
        String c = loadConfigContent(appId, namespace);
        return YamlReader.parseContent(c);
    }


    public static Map<String, Object> loadApolloConfigs(final String appId, final String namespaces) {
        String[] namespaceArr = namespaces.split(",");

        final String firstNamespace = namespaceArr[0];
        final Map<String, Object> firstConfigMap = loadApolloConfig(appId, firstNamespace);

        for (int i=1; i<namespaceArr.length; ++i) {
            final String curNamespace = namespaceArr[i];

            final Map<String, Object> configMap2 = loadApolloConfig(appId, curNamespace);

            YamlPropertiesUtils.mergeProperties(firstConfigMap, firstNamespace, configMap2, curNamespace, false, true);
        }
        return firstConfigMap;
    }


    public static void main(String[] args) {

    }
}
